<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { DynamicTableInstance } from "@/components/DynamicTable/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import { FormItemConfig } from "@/components/DynamicForm/types";

const props = defineProps<{
  task: string;
}>();

defineOptions({
  name: "Result",
});

// 表单引用
const searchFormRef = ref<DynamicFormInstance>();
const tableRef = ref<DynamicTableInstance>();

// 页面数据
const loading = ref(false);

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  pageSizes: [10, 20, 50],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

// 搜索表单数据
const searchFormData = reactive({
  asset_name: "",
  exposure_asset_ip: "",
  open_port: "",
  department: "",
  status: "",
});

// 搜索表单配置
const searchFormConfig: FormItemConfig[] = [
  {
    type: "input",
    key: "asset_name",
    name: "资产名称",
    placeholder: "资产名称",
    params: {
      clearable: true,
    },
  },
  {
    type: "input",
    key: "exposure_asset_ip",
    name: "暴露面IP",
    placeholder: "暴露面IP",
    params: {
      clearable: true,
    },
  },
  {
    type: "input",
    key: "open_port",
    name: "开放端口",
    placeholder: "开放端口",
    params: {
      clearable: true,
    },
  },
];

// 表格数据
const tableData = ref([]);

// 表格列配置
const tableColumns: TableColumn[] = [
  {
    label: "资产名称",
    prop: "asset_name",
    show: true,
    key: "asset_name",
  },
  {
    label: "暴露面资产IP",
    prop: "exposure_asset_ip",
    show: true,
    key: "exposure_asset_ip",
    slot: "exposure_asset_ip",
  },
  {
    label: "开放端口",
    prop: "open_port",
    show: true,
    key: "open_port",
  },
  {
    label: "疑似所属部门",
    prop: "department",
    show: true,
    key: "department",
  },
  {
    label: "状态",
    prop: "status",
    show: true,
    key: "status",
    slot: "status",
  },
  {
    label: "操作",
    prop: "action",
    show: true,
    key: "action",
    fixed: "right",
    slot: "action",
  },
];

// 原始数据
const originalData = [
  {
    id: 1,
    asset_name: "Web服务器-01",
    exposure_asset_ip: "192.168.1.100",
    open_port: "80,443,22",
    department: "技术部",
    status: "未下发",
  },
  // {
  //   id: 2,
  //   asset_name: "数据库服务器-02",
  //   exposure_asset_ip: "192.168.1.101",
  //   open_port: "3306,22",
  //   department: "技术部",
  //   status: "已下发",
  // },
  // {
  //   id: 3,
  //   asset_name: "API服务器-03",
  //   exposure_asset_ip: "192.168.1.102",
  //   open_port: "8080,22",
  //   department: "开发部",
  //   status: "未下发",
  // },
  // {
  //   id: 4,
  //   asset_name: "文件服务器-04",
  //   exposure_asset_ip: "192.168.1.103",
  //   open_port: "21,22",
  //   department: "运维部",
  //   status: "已下发",
  // },
  // {
  //   id: 5,
  //   asset_name: "邮件服务器-05",
  //   exposure_asset_ip: "192.168.1.104",
  //   open_port: "25,110,143",
  //   department: "技术部",
  //   status: "未下发",
  // },
];

// 获取扫描结果列表
const getScanResultList = async () => {
  loading.value = true;

  // 模拟API调用延迟
  setTimeout(() => {
    let filteredData = [...originalData];

    // 根据搜索条件过滤数据
    if (searchFormData.asset_name) {
      filteredData = filteredData.filter((item) =>
        item.asset_name.includes(searchFormData.asset_name)
      );
    }

    if (searchFormData.exposure_asset_ip) {
      filteredData = filteredData.filter((item) =>
        item.exposure_asset_ip.includes(searchFormData.exposure_asset_ip)
      );
    }

    if (searchFormData.open_port) {
      filteredData = filteredData.filter((item) =>
        item.open_port.includes(searchFormData.open_port)
      );
    }

    if (searchFormData.department) {
      filteredData = filteredData.filter((item) =>
        item.department.includes(searchFormData.department)
      );
    }

    if (searchFormData.status) {
      filteredData = filteredData.filter(
        (item) => item.status === searchFormData.status
      );
    }

    // 模拟分页
    const start = (pagination.currentPage - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    tableData.value = filteredData.slice(start, end);
    pagination.total = filteredData.length;

    loading.value = false;
  }, 300);
};

// 搜索
const handleSearch = (value: any) => {
  pagination.currentPage = 1;
  getScanResultList();
};

// 重置搜索
const handleSearchReset = () => {
  searchFormRef.value?.resetFields();
  getScanResultList();
};

// 分页处理
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  getScanResultList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  getScanResultList();
};

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm("确定要删除选中的记录吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ElMessage.success("删除成功");
      getScanResultList();
    })
    .catch(() => {
      // 取消删除
    });
};

// 导出结果
const handleExport = () => {
  ElMessage.success("导出成功");
};

// 获取状态标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case "已下发":
      return "success";
    case "未下发":
      return "warning";
    default:
      return "info";
  }
};

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  console.log("选中的记录:", selection);
};

// 下发工单
const handleIssueWorkOrder = async (row: any) => {
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 更新状态为已下发
    const index = tableData.value.findIndex((item) => item.id === row.id);
    if (index !== -1) {
      tableData.value[index].status = "已下发";
    }

    ElMessage.success(`资产"${row.asset_name}"工单下发成功！`);

    console.log("下发工单:", row);
  } catch (error) {
    console.error("下发工单失败:", error);
    ElMessage.error("下发工单失败");
  }
};

onMounted(() => {
  getScanResultList();
});
</script>

<template>
  <div>
    <!-- 搜索表单 -->
    <el-card shadow="never">
      <!-- <div class="search-form-container"> -->
      <DynamicForm
        ref="searchFormRef"
        v-model="searchFormData"
        :form-config="searchFormConfig"
        :gutter="16"
        label-width="80px"
        type="search"
        @search="handleSearch"
        @reset="handleSearchReset"
      />
      <!-- <div class="search-actions">
          <el-button type="success" @click="handleExport">导出结果</el-button>
          <el-button type="danger" @click="handleBatchDelete"
            >批量删除</el-button
          >
        </div> -->
      <!-- </div> -->
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="never" class="mt-4">
      <DynamicTable
        ref="tableRef"
        :data="tableData"
        :columns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        :showToolbar="true"
        border
        @current-page-change="handlePageChange"
        @size-change="handleSizeChange"
        @selection-change="handleSelectionChange"
      >
        <!-- 暴露面IP列插槽 -->
        <template #exposure_asset_ip="{ row }">
          <el-tag type="success" effect="plain">
            {{ row.exposure_asset_ip }}
          </el-tag>
        </template>

        <!-- 状态列插槽 -->
        <template #status="{ row }">
          <el-tag :type="getStatusType(row.status)" effect="dark">
            {{ row.status }}
          </el-tag>
        </template>

        <!-- 操作列插槽 -->
        <template #action="{ row }">
          <el-button
            size="small"
            type="primary"
            :disabled="row.status === '已下发'"
            @click="handleIssueWorkOrder(row)"
          >
            下发工单
          </el-button>
        </template>
      </DynamicTable>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-card__header) {
}

:deep(.el-pagination) {
  justify-content: right;
  margin-top: 10px;
  margin-right: 30px;
}

.ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.confidence-text {
  font-size: 12px;
  color: #606266;
  margin-left: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.demo-form-inline .el-form-item {
  margin-right: 20px;
  margin-bottom: 10px;
}

.demo-form-inline .el-form-item:last-child {
  margin-right: 0;
}

.search-form-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  flex-wrap: wrap;
  gap: 16px;
}

.search-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}
</style>
